<template>
  <div class="container-certify">
    <div class="wrap">
      <el-button :icon="ArrowLeftBold" text @click="back">退出认证</el-button>
      <div class="certify-box">
        <div class="top">
          <div class="title">
            欢迎认证·
            <strong>个人认证</strong>
          </div>
          <div class="step">
            <div class="step-item" :class="{ active: step == 1 }">
              <div class="step-item-icon">1</div>
              <div class="step-item-title">认证方式</div>
            </div>
            <div class="step-item" :class="{ active: step == 2 }">
              <div class="step-item-icon">2</div>
              <div class="step-item-title">完成认证</div>
            </div>
          </div>
          <img src="../assets/enterprise/renzheng_icon.png" />
        </div>
        <div class="content">
          <div class="inner">
            <div class="tip" v-if="step < 2">
              <img src="../assets/enterprise/renzheng_icon1.png" />
              <span>您填写的信息仅用于完成本次认证，平台方不会留存或泄露，请放心填写。</span>
            </div>
            <el-form :model="form" ref="ruleFormRef" :rules="rules" :inline="true" label-width="100px" v-if="step == 1">
              <el-row :span="24">
                <el-col :span="24">
                  <el-form-item prop="realName" style="width: 100%" label="姓名">
                    <el-input v-model="form.realName" style="width: 100%" placeholder="请输入" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="idCardNo" style="width: 100%" label="身份证号">
                    <el-input v-model="form.idCardNo" style="width: 100%" placeholder="请输入" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="mobile" style="width: 100%" label="手机号">
                    <el-input v-model="form.mobile" placeholder="请输入手机号" style="flex: 1; margin-right: 5px" />
                    <el-button :disabled="countDisabled" @click="getCode">{{ countText }}</el-button>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item prop="code" style="width: 100%" label="验证码">
                    <el-input v-model="form.code" style="width: 100%" placeholder="请输入" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item style="width: 100%">
                <el-button class="submit" @click="submitForm(ruleFormRef)" :loading="loading">确定</el-button>
              </el-form-item>
            </el-form>
            <div class="certify-success" v-if="step == 2">
              <img src="../assets/enterprise/success.png" />
              <el-button class="submit" @click="back">完成认证</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { getArea, userAuth } from "@/api/index";
  import { useUserStore } from "@/store/user";
  import { ArrowLeftBold } from "@element-plus/icons-vue";
  import type { FormInstance } from "element-plus";
  import { computed, onMounted, reactive, ref, nextTick } from "vue";
  import { useRouter } from "vue-router";
  import { authPersonMobile3, authCaptchaVerify } from "@/api/cf";

  const router = useRouter();
  const countDisabled = ref(false);
  const countText = ref("获取验证码");
  type Area = {
    id: number;
    name: string;
    level: number;
    parent_id: number;
    city_id: number;
  };
  const loading = ref(false);
  const form = reactive({
    id: null,
    realName: null,
    idCardNo: null,
    mobile: null,
    code: null,
    type: null,
  });
  const validateIDCard = (rule: any, value: string, callback: any) => {
    if (!value) {
      callback(new Error("请输入身份证号"));
      return;
    }

    const idCardRegex = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;

    if (!idCardRegex.test(value)) {
      callback(new Error("身份证号格式不正确"));
      return;
    }

    const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    const checkCodes = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"];
    let sum = 0;

    for (let i = 0; i < 17; i++) {
      sum += parseInt(value[i]) * weights[i];
    }

    const lastChar = value[17].toUpperCase();
    if (lastChar !== checkCodes[sum % 11]) {
      callback(new Error("身份证号校验失败，请检查"));
    } else {
      callback();
    }
  };

  const validateMobile = (rule: any, value: string, callback: any) => {
    if (!value) {
      callback(new Error("请输入手机号"));
      return;
    }

    const mobileRegex = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;

    if (!mobileRegex.test(value)) {
      callback(new Error("请输入正确的11位手机号"));
    } else {
      callback();
    }
  };
  const ruleFormRef = ref<FormInstance>();

  const rules = reactive({
    realName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
    code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
   idCardNo: [{ required: true, validator: validateIDCard, trigger: ["blur", "change"] }],
    mobile: [{ required: true, validator: validateMobile, trigger: ["blur", "change"] }],
  });

  const step = ref(1);
  const areaData = ref<Area[]>([]);
  const provinceList = computed(() => {
    return areaData.value.filter(item => item.parent_id == 0);
  });
  const cityList = computed(() => {
    return areaData.value.filter(item => item.parent_id == form.province_id);
  });
  const areaList = computed(() => {
    return areaData.value.filter(item => item.parent_id == form.city_id);
  });

  const userStore = useUserStore();

  const back = () => {
    router.back();
  };

  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
      if (valid) {
        loading.value = true;
        authCaptchaVerify({
         code:form.code,
         type:1,
         id:form.id
        })
          .then(res => {
            step.value = 2;
            loading.value = false;
          })
          .catch(err => {
            loading.value = false;
            console.log(err);
          });
      } else {
        console.log("error submit!", fields);
      }
    });
  };

  onMounted(() => {
    nextTick(() => {
      form.id = userStore.userInfo.id;
    });

    console.log(form.value, "sgsgggg");
  });

  const getCode = () => {
    if (form.realName === null) {
      ElMessage.error("请输入姓名");
      return;
    }
    if (form.idCardNo ===  null) {
      ElMessage.error("请输入身份证号");
      return;
    }
    if (form.mobile ===  null) {
      ElMessage.error("请输入手机号");
      return;
    }else{
    if (!/^1[3456789]\d{9}$/.test(form.mobile)) {
      ElMessage.error("手机号格式不正确");
      return;
    }
    }
  

    countDisabled.value = true;
    authPersonMobile3({
      id: form.id,
      realName: form.realName,
      idCardNo: form.idCardNo,
      mobile: form.mobile,
    }).then(() => {
      ElMessage.success("发送成功");
      let currentTime = 60;
      countText.value = "60S重新获取";
      let interval = setInterval(() => {
        currentTime--;
        countText.value = currentTime + "S" + "重新获取";
        if (currentTime <= 0) {
          clearInterval(interval);
          countText.value = "重新获取";
          countDisabled.value = false;
        }
      }, 1000);
    }).catch(err => {
       countDisabled.value = true;
    });
  };
</script>
<style lang="scss" scoped>
.container-certify {
  width: 100%;
  height: calc(100vh - 96px);
  background: #f5f5f5;

  .wrap {
    width: 980px;
    margin: 0 auto;
    padding-top: 25px;

    .certify-box {
      margin-top: 20px;
      border-radius: 10px;
      background-color: #fff;
      overflow: hidden;

      .top {
        height: 132px;
        background-image: linear-gradient(#f3f9ff, #e6f1ff);
        position: relative;

        img {
          width: 108px;
          height: 116px;
          position: absolute;
          top: 15px;
          right: 50px;
        }

        .title {
          font-size: 20px;
          color: #01509f;
          text-align: center;
          padding-top: 20px;

          strong {
            font-weight: 600;
          }
        }

        .step {
          display: flex;
          justify-content: space-between;
          width: 280px;
          margin: 25px auto 0;

          .step-item {
            display: flex;
            justify-content: center;
            flex-direction: column;
            align-items: center;
            position: relative;
            width: 90px;

            &:nth-child(1)::after {
              content: "";
              position: absolute;
              top: 8px;
              right: -84px;
              width: 66px;
              height: 1px;
              background-color: #dee2e6;
            }

            .step-item-icon {
              font-size: 12px;
              text-align: center;
              width: 16px;
              height: 16px;
              line-height: 16px;
              border-radius: 50%;
              color: #9e9f9f;
              border: solid 1px #9e9f9f;
            }

            .step-item-title {
              font-size: 14px;
              color: #666;
              margin-top: 10px;
            }

            &.active {
              .step-item-icon {
                border-color: #77aeff;
                color: #fff;
                background-color: #77aeff;
              }

              .step-item-title {
                color: #01509f;
              }

              &:nth-child(1)::after {
                background-color: #77aeff;
              }
            }
          }
        }
      }

      .content {
        padding: 25px 0 30px;
        max-height: calc(100vh - 400px);
        overflow: auto;

        .inner {
          width: 567px;
          margin: 0 auto;

          .tip {
            height: 38px;
            display: flex;
            align-items: center;
            background-color: #f3f8fb;
            border-radius: 5px;
            margin-bottom: 30px;

            img {
              width: 12px;
              height: 16px;
              margin: 0 4px 0 12px;
            }

            span {
              font-size: 12px;
              color: #999;
            }
          }

          .formitem {
            width: 100%;
            display: flex;
            margin-bottom: 15px;

            .label {
              width: 136px;
              text-align: right;
              margin-right: 16px;
              line-height: 20px;
              font-size: 14px;
              color: #666;
              flex-shrink: 0;

              span {
                color: #f00;
              }
            }
          }

          .submit {
            width: 200px;
            height: 37px;
            color: #fff;
            background-color: #01509f;
            margin: 25px auto 0;
          }

          .change {
            font-size: 14px;
            text-align: center;
            margin-top: 10px;

            span {
              color: #01509f;
              cursor: pointer;
            }
          }

          .license {
            width: 466px;
            margin: 0 auto;
            display: flex;
            align-items: flex-end;

            span {
              font-size: 14px;
              color: #666;
              height: 178px;
            }

            .avatar-uploader {
              width: 288px;
              height: 178px;
              margin: 0 16px;

              .avatar {
                width: 288px;
                height: 178px;
                display: block;
              }

              :deep(.el-upload) {
                width: 286px;
                height: 176px;
                border: 1px dashed #ddd;
                border-radius: 6px;
                cursor: pointer;
                position: relative;
                overflow: hidden;
                transition: var(--el-transition-duration-fast);
              }

              .el-upload:hover {
                border-color: var(--el-color-primary);
              }

              .el-icon.avatar-uploader-icon {
                font-size: 38px;
                color: #ccc;
                width: 288px;
                height: 178px;
                text-align: center;
              }

              .el-icon.is-loading {
                animation: rotating 2s linear infinite;
              }

              @keyframes rotating {
                from {
                  transform: rotate(0deg);
                }

                to {
                  transform: rotate(360deg);
                }
              }
            }
          }

          .certify-success {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;

            img {
              width: 120px;
              height: 87px;
              margin: 50px 0 30px;
            }

            .submit {
              width: 200px;
              height: 37px;
              color: #fff;
              background-color: #01509f;
              margin: 25px auto 0;
            }
          }
        }
      }
    }
  }
}
</style>
